<?php
namespace Admin\Models;

use Helpers\Main;
use Helpers\User;
use Phalcon\Mvc\Model;
use Phalcon\Di;
use Phalcon\Mvc\Model\Behavior\SoftDelete;

class BaseModel extends Model
{

    /**
     * 初始化软删除
     *
     * create by ck 20160701
     */
    public function initialize()
    {
        $this->useDynamicUpdate(true);
//        $this->keepSnapshots(false);
        $this->addBehavior(new SoftDelete(
            array(
                'field' => 'bDelete',
                'value' => 1,
            )
        ));
    }

    /**
     * 获取保存错误原因
     *
     * @return string
     *
     * create by ck 20180320
     */
    public function getError()
    {
        $message = parent::getMessages()[0];
        return $message->getMessage();

//        $messages = [];
//
//        foreach (parent::getMessages() as $message) {
//            switch ($message->getType()) {
//                case "InvalidCreateAttempt":
//                    $messages[] = "The record cannot be created because it already exists";
//                    break;
//
//                case "InvalidUpdateAttempt":
//                    $messages[] = "The record cannot be updated because it doesn't exist";
//                    break;
//
//                case "PresenceOf":
//                    $messages[] = "The field " . $message->getField() . " is mandatory";
//                    break;
//            }
//        }
//
//        return $messages;
    }

    /**
     * 根据id字段及数组删除记录
     *
     * @param $idField
     * @param $idArr
     * @return bool
     *
     * create by ck 20170722
     */
    public static function deleteRecord($idField, $idArr)
    {
        if (!$idField || !$idArr || !is_string($idField)) {
            return false;
        }
        is_string($idArr) and $idArr = explode(',', $idArr);
//        $db     = self::getWriteConnection();
//        $table  = self::getSource();
        return self::find([
            'conditions' => "bDelete = 0 AND {$idField} IN ({idArr:array})",
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

    /**
     * 根据id删除记录
     *
     * @param $idArr
     * @return bool
     *
     * create by ck 20180322
     */
    public static function deleteById($idArr)
    {
        if (!$idArr) {
            return false;
        }
        is_string($idArr) and $idArr = array_filter(explode(',', $idArr));
        return self::find([
            'conditions' => "bDelete = 0 AND id IN ({idArr:array})",
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

    /**
     * 创建前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20170316
     */
    public function beforeCreate()
    {
        $userId  = User::getId();
        $time    = date('Y-m-d H:i:s');
        if (property_exists($this, 'bDelete')) {
            $this->writeAttribute('bDelete', 0);
        }
        if (property_exists($this, 'tCreateDate')) {
            $this->writeAttribute('tCreateDate', $time);
        }
        if (property_exists($this, 'iCreateUserId')) {
            $this->writeAttribute('iCreateUserId', $userId);
        }
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return true;
    }

    /**
     * 更新前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20170316
     */
    public function beforeUpdate()
    {
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', User::getId());
        }
        return true;
    }

    /**
     * 删除前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20160701
     * modify by ck 20170224    判断方法更改 isset->property_exists
     */
    public function beforeDelete()
    {
        $this->beforeUpdate();
        return true;
    }

    /**
     * 新增/修改记录，如主键值为空则为新增，添加相应字段数据
     *
     * @param bool|false $new
     * @return bool
     *
     * create by ck 20170314
     */
    public function modifyData($new = false)
    {
        $userId  = Main::getLoginUserInfo('userId');
        $time    = date('Y-m-d H:i:s');
        if ($new) {
            if (property_exists($this, 'bDelete')) {
                $this->writeAttribute('bDelete', 0);
            }
            if (property_exists($this, 'tCreateDate')) {
                $this->writeAttribute('tCreateDate', $time);
            }
            if (property_exists($this, 'iCreateUserId')) {
                $this->writeAttribute('iCreateUserId', $userId);
            }
        }
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', $time);
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return $this->save();
    }

    /**
     * 插入数据前检查是否需要添加创建时间等信息
     *
     * @return bool
     *
     * create by ck 20170223
     * modify by ck 20170224    判断方法更改 isset->property_exists
     */
    public function insertData()
    {
        $userId  = Main::getLoginUserInfo('userId');
        $time    = date('Y-m-d H:i:s');
        if (property_exists($this, 'bDelete')) {
            $this->writeAttribute('bDelete', 0);
        }
        if (property_exists($this, 'tCreateDate')) {
            $this->writeAttribute('tCreateDate', $time);
        }
        if (property_exists($this, 'iCreateUserId')) {
            $this->writeAttribute('iCreateUserId', $userId);
        }
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', $time);
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return $this->save();
    }

    /**
     * 更新数据前检查是否需要修改更新时间及更新人
     *
     * @return bool
     *
     * create by ck 20170223
     * modify by ck 20170224    判断方法更改 isset->property_exists
     */
    public function updateData()
    {
        $userId = Main::getLoginUserInfo('userId');
        $time   = date('Y-m-d H:i:s');
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', $time);
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return $this->save();
    }

}